﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.IO.IsolatedStorage;
using System.Collections.Generic;

namespace Phone.Framework.Data
{


    public class IsolatedStorageSettingCollection<T>:ObservableCollection<T>,IAutoSave
    {
        private static IsolatedStorageSettings set = IsolatedStorageSettings.ApplicationSettings;

        private string _cacheKey;
        private IsolatedStorageSettingCollection()
        {
           
        }

        public IsolatedStorageSettingCollection(string cacheKey, IEnumerable<T> collection)
            : base(collection)
        {
            _cacheKey = cacheKey;
        }

        public static IsolatedStorageSettingCollection<T> CreateEmptyCollection(string cacheKey)
        {
            List<T> list = null;
            list = new List<T>();
            set[cacheKey] = list;
            set.Save();
            return new IsolatedStorageSettingCollection<T>(cacheKey, list);
        }

        public static IsolatedStorageSettingCollection<T> CreateCollection(string cacheKey)
        {
            List<T> list = null;
            if (set.Contains(cacheKey))
            {
                list = (List<T>)set[cacheKey];
            }
            else
            {
                list = new List<T>();
                set[cacheKey] = list;
                set.Save();
            }
            return new IsolatedStorageSettingCollection<T>(cacheKey,list);
        }

        public static void DeleteCollection(string cacheKey)
        {
            set.Remove(cacheKey);
            set.Save();
        }

        public void Save()
        {
            set[_cacheKey]=new List<T>(this);
            set.Save();
        }
    }
}
